package cn.krui.project.controller.system;

import java.util.HashMap;
import java.util.Map;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.krui.helper.bean.AppResult;
import cn.krui.helper.bean.DataArray;
import cn.krui.helper.bean.DataSingle;
import cn.krui.helper.db.DBHelper;
import cn.krui.helper.db.SQL;
import cn.krui.helper.tools.RedisUtils;
import cn.krui.helper.tools.SecurityUtils;
import cn.krui.project.bean.system.sys_role.sys_role;
import cn.krui.project.bean.system.sys_user.sys_user_info;
import cn.krui.project.service.system.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @program: project-system
 * @description: 用户模块
 * @author: zc
 * @create: 2019-10-10 16:05
 **/
@Api(tags = "管理-管理端用户", description = "系统用户模块接口")
@RestController
@RequestMapping("/system/sysuser")
@CrossOrigin
public class SysUserController extends SystemBaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DBHelper dbHelper;

    @Autowired
    private RedisUtils redisUtils;

    private final Integer EQUALS_MOBILE_LENGTH = 11;
    private final String EQUALS_INIT_DEFAULT = "init_default";
    private final String EQUALS_INIT_DEFAULT_VALUE = "1";

    /**
     * 用户列表
     */
    @PostMapping(value = "/getSysUserList")
    @ApiOperation(value = "获取用户列表", httpMethod = "POST")
    public AppResult<sys_user_info> getSysUserList(
            @ApiParam(value = "部门id", required = false) @RequestParam(value = "dept_id", required = false) Integer dept_id,
            @ApiParam(value = "角色id", required = false) @RequestParam(value = "role_id", required = false) Integer role_id,
            @ApiParam(value = "员工编号", required = false) @RequestParam(value = "user_number", required = false) String user_number,
            @ApiParam(value = "员工登录账号", required = false) @RequestParam(value = "user_name", required = false) String user_name,
            @ApiParam(value = "员工真实姓名", required = false) @RequestParam(value = "real_name", required = false) String real_name,
            @ApiParam(value = "电话", required = false) @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(value = "性别", required = false) @RequestParam(value = "gender", required = false) String gender,
            @ApiParam(value = "状态", required = false) @RequestParam(value = "status", required = false) String status,
            @ApiParam(value = "页", required = true) @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(value = "条", required = true) @RequestParam(value = "size", required = true) Integer size) {
        AppResult<sys_user_info> app = new AppResult<sys_user_info>();
        DataSingle<sys_user_info> where = new DataSingle<>();
        sys_user_info sysUserInfo = new sys_user_info();
        sysUserInfo.setDept_id(dept_id);
        sysUserInfo.setRole_id(role_id);
        sysUserInfo.setUser_number(user_number);
        sysUserInfo.setUser_name(user_name);
        sysUserInfo.setMobile(mobile);
        sysUserInfo.setGroup_id(getUser().getUid());
        where.setDataSingle(sysUserInfo);
        where.setPageIndex(page);
        where.setPageSize(size);
        DataArray<sys_user_info> list = sysUserService.selectSysUserList(where);
        app.ok();
        app.setDataArray(list);
        app.setMsg("获取成功");
        return app;
    }

    /**
     * 添加用户
     * 
     * @throws NoSuchAlgorithmException
     */
    @PostMapping(value = "/addSysUser")
    @ApiOperation(value = "添加用户", httpMethod = "POST")
    public AppResult<sys_role> addSysUser(
            @ApiParam(value = "部门id", required = true) @RequestParam(value = "dept_id", required = true) String dept_id,
            @ApiParam(value = "角色id", required = true) @RequestParam(value = "role_id", required = true) String role_id,
            @ApiParam(value = "员工登录账号", required = true) @RequestParam(value = "user_name", required = true) String user_name,
            @ApiParam(value = "员工登录密码", required = false) @RequestParam(value = "passwd", required = false) String passwd,
            @ApiParam(value = "员工真实姓名", required = false) @RequestParam(value = "real_name", required = false) String real_name,
            @ApiParam(value = "电话", required = false) @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(value = "性别", required = false) @RequestParam(value = "gender", required = false) String gender,
            @ApiParam(value = "email", required = false) @RequestParam(value = "email", required = false) String email)
            throws NoSuchAlgorithmException {
        AppResult<sys_role> app = new AppResult<sys_role>();
        sys_user_info sysUserInfo = new sys_user_info();
        if (!StringUtils.isEmpty(dept_id)) {
            sysUserInfo.setDept_id(Integer.parseInt(dept_id));
        }
        if (!StringUtils.isEmpty(role_id)) {
            sysUserInfo.setRole_id(Integer.parseInt(role_id));
        }
        if (!StringUtils.isEmpty(user_name)) {
            sysUserInfo.setUser_name(user_name);
            sys_user_info sysUser = sysUserService.selectSysUserbyUserName(sysUserInfo);
            if (sysUser != null) {
                app.no("");
                app.setMsg("用户名存在,请重新输入");
                return app;
            }
        }
        if (!StringUtils.isEmpty(passwd)) {
            sysUserInfo.setPasswd(SecurityUtils.md5(passwd));
        } else {
            sysUserInfo.setPasswd(SecurityUtils.md5("123123"));
        }
        if (!StringUtils.isEmpty(real_name)) {
            sysUserInfo.setReal_name(real_name);
        }
        if (!StringUtils.isEmpty(mobile)) {
            if (mobile.length() != EQUALS_MOBILE_LENGTH) {
                app.no("");
                app.setMsg("手机号长度为11位");
                return app;
            }
            sysUserInfo.setMobile(mobile);
        }
        if (!StringUtils.isEmpty(gender)) {
            sysUserInfo.setGender(gender);
        }
        if (!StringUtils.isEmpty(email)) {
            sysUserInfo.setEmail(email);
        }
        sysUserInfo.setCreate_time(new Timestamp(System.currentTimeMillis()));
        sysUserInfo.setStatus(1);
        Integer i = sysUserService.addSysUser(sysUserInfo);
        if (i > 0) {
            app.ok();
            app.setMsg("添加成功");
        } else {
            app.no("");
            app.setMsg("添加失败");
        }
        return app;
    }

    /**
     * 更改用户
     */
    @PostMapping(value = "/updateSysUser")
    @ApiOperation(value = "更改用户", httpMethod = "POST")
    public AppResult<sys_role> updateSysUser(
            @ApiParam(value = "部门id", required = false) @RequestParam(value = "dept_id", required = false) String dept_id,
            @ApiParam(value = "角色id", required = false) @RequestParam(value = "role_id", required = false) String role_id,
            @ApiParam(value = "员工真实姓名", required = false) @RequestParam(value = "real_name", required = false) String real_name,
            @ApiParam(value = "电话", required = false) @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(value = "性别", required = false) @RequestParam(value = "gender", required = false) String gender,
            @ApiParam(value = "email", required = false) @RequestParam(value = "email", required = false) String email,
            @ApiParam(value = "id", required = true) @RequestParam(value = "id", required = true) String id,
            @ApiParam(value = "状态", required = false) @RequestParam(value = "status", required = false) String status,
            @ApiParam(value = "员工登录账号", required = false) @RequestParam(value = "user_name", required = false) String user_name,
            @ApiParam(value = "员工登录密码", required = false) @RequestParam(value = "passwd", required = false) String passwd) {
        AppResult<sys_role> app = new AppResult<sys_role>();
        sys_user_info sysUserInfo = new sys_user_info();
        if (!StringUtils.isEmpty(dept_id)) {
            sysUserInfo.setDept_id(Integer.parseInt(dept_id));
        }
        if (!StringUtils.isEmpty(role_id)) {
            sysUserInfo.setRole_id(Integer.parseInt(role_id));
        }
        if (!StringUtils.isEmpty(real_name)) {
            sysUserInfo.setReal_name(real_name);
        }
        if (!StringUtils.isEmpty(mobile)) {
            sysUserInfo.setMobile(mobile);
        }
        if (!StringUtils.isEmpty(gender)) {
            sysUserInfo.setGender(gender);
        }
        if (!StringUtils.isEmpty(status)) {
            sysUserInfo.setStatus(Integer.parseInt(status));
        }
        if (!StringUtils.isEmpty(email)) {
            sysUserInfo.setEmail(email);
        }
        sysUserInfo.setId(Integer.parseInt(id));
        if (!StringUtils.isEmpty(user_name)) {
            sysUserInfo.setUser_name(user_name);
            sys_user_info sysUser = sysUserService.selectSysUserbyUserName(sysUserInfo);
            if (sysUser != null) {
                app.no("");
                app.setMsg("用户名存在,请重新输入");
                return app;
            }
        }
        if (!StringUtils.isEmpty(passwd)) {
            sysUserInfo.setPasswd(passwd);
        }

        Integer i = sysUserService.updateSysUser(sysUserInfo);
        if (i > 0) {
            app.ok();
            app.setMsg("更新成功");
        } else {
            app.no("");
            app.setMsg("更新失败");
        }
        return app;
    }

    /**
     * 删除用户
     */
    @PostMapping(value = "/deleteSysUser")
    @ApiOperation(value = "删除用户", httpMethod = "POST")
    public AppResult<sys_role> deleteSysUser(
            @ApiParam(value = "主键id", required = true) @RequestParam(value = "id", required = true) String id) {
        AppResult<sys_role> app = new AppResult<sys_role>();
        SQL.SelectSQL sql = SQL.select("init_default").from("qr_sys_users").where("id=#{id}").addParameter("id", id);
        Map<String, Object> map = dbHelper.selectOne(sql);
        if (EQUALS_INIT_DEFAULT_VALUE.equals(map.get(EQUALS_INIT_DEFAULT))) {
            app.no("");
            app.setMsg("系统内置数据无法删除");
            return app;
        }
        Map<String, Object> where = new HashMap<>(1);
        where.put("id", id);
        sys_user_info sysUserInfo = dbHelper.selectOne("id,token", "qr_sys_users", "id=#{id}", where,
                sys_user_info.class);
        sysUserInfo.setId(Integer.parseInt(id));
        Integer i = sysUserService.deleteSysUser(sysUserInfo);
        if (i > 0) {
            app.ok();
            app.setMsg("删除成功");
            // 清除登录凭证
            redisUtils.delete(String.format("login_token:%s", sysUserInfo.getToken()));
        } else {
            app.no("");
            app.setMsg("删除失败");
        }
        return app;
    }

    /**
     * 修改密码
     * 
     * @throws NoSuchAlgorithmException
     */
    @PostMapping(value = "/changePsd")
    @ApiOperation(value = "修改密码", httpMethod = "POST")
    public AppResult<sys_role> changePsd(
            @ApiParam(value = "主键id", required = true) @RequestParam(value = "id", required = true) String id,
            @ApiParam(value = "密码", required = true) @RequestParam(value = "password", required = true) String password,
            @ApiParam(value = "确认密码", required = true) @RequestParam(value = "repassword", required = true) String repassword)
            throws NoSuchAlgorithmException {
        AppResult<sys_role> app = new AppResult<sys_role>();

        Map<String, Object> where = new HashMap<>(1);
        where.put("id", id);
        sys_user_info sysUserInfo = dbHelper.selectOne("id,token", "qr_sys_users", "id=#{id}", where,
                sys_user_info.class);
        if (!password.equals(repassword)) {
            app.no("");
            app.setMsg("两次输入密码不相同");
            return app;
        }
        sysUserInfo.setId(Integer.parseInt(id));
        sysUserInfo.setPasswd(SecurityUtils.md5(password));

        Integer i = sysUserService.updateSysUser(sysUserInfo);
        if (i <= 0) {
            app.no("");
            app.setMsg("修改失败");
        }
        app.ok();
        app.setMsg("修改成功,下次登录请使用新密码进行登录");
        // 清除登录凭证
        redisUtils.delete(String.format("login_token:%s", sysUserInfo.getToken()));
        return app;
    }

}
